﻿using System;
using System.Collections.Generic;
using System.Data.Objects.SqlClient;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using HYBYSoft.Company.Models;
using HYBYSoft.Company.WebSite.Helper;

namespace HYBYSoft.Company.WebSite.Areas.Admin.Controllers
{
    public class ArticleController : Controller
    {
        /// <summary>
        /// 数据库实体上下文对象
        /// </summary>
        CompanySiteEntities _dbContext = new CompanySiteEntities();

        /// <summary>
        /// 文章首页
        /// </summary>
        /// <returns></returns>
        [Authentication]
        public ActionResult Index(string titleDetail, int? ddlCategoryName, DateTime? startTime, DateTime? endTime)
        {
            //绑定分类下拉框
            var categoryNamelist = LoadCategoryName();
            categoryNamelist.Insert(0, new SelectListItem { Value = "0", Text = "全部" });
            ViewData["categoryName"] = categoryNamelist;

            //获得查询条件
            string title = titleDetail ?? string.Empty;
            int category = ddlCategoryName.HasValue ? ddlCategoryName.Value : 0;
            DateTime start = startTime.HasValue ? startTime.Value : DateTime.MinValue;
            DateTime end = endTime.HasValue ? endTime.Value : DateTime.MaxValue;

            //根据查询条件获得数据
            var articlelist = (from a in _dbContext.Articles
                               join c in _dbContext.Categories on a.CategoryID equals c.CategoryID
                               where a.Title.Contains(title) && (category == 0 || c.CategoryID == category) && (a.CreateTime >= start && a.CreateTime <= end)
                               orderby a.LastEditTime descending
                               select new ArticleAndCategory
                               {
                                   ArticleID = a.ArticleID,
                                   Title = a.Title,
                                   Editor = a.Editor,
                                   Contents = a.Contents,
                                   Icon = a.Icon,
                                   Description = a.Description,
                                   CreateTime = a.CreateTime,
                                   LastEditor = a.LastEditor,
                                   LastEditTime = a.LastEditTime,
                                   ControllorName = a.ControllorName,
                                   ActionName = a.ActionName,
                                   IsRelease = a.IsRelease,
                                   Release = a.IsRelease == 0 ? "未发布" : "发布",
                                   CategoryName = c.Name
                               });

            return View(articlelist);
        }

        /// <summary>
        /// 绑定分类下拉框
        /// </summary>
        private List<SelectListItem> LoadCategoryName()
        {
            var categoryNamelist = (from c in _dbContext.Categories
                                    where c.State != 0
                                    select new SelectListItem
                                    {
                                        Value = SqlFunctions.StringConvert((double)c.CategoryID),
                                        Text = c.Name
                                    }).ToList<SelectListItem>();

            return categoryNamelist;
        }

        /// <summary>
        /// 根据条件查询文章信息
        /// </summary>
        /// <returns></returns>
        [HttpPost, Authentication]
        public ActionResult Search()
        {
            return RedirectToAction("Index", new { titleDetail = Request["titleDetail"], ddlCategoryName = int.Parse(Request["ddlCategoryName"]), startTime = Request["startTime"], endTime = Request["endTime"] });
        }

        /// <summary>
        /// 文章发布管理
        /// </summary>
        /// <param name="id">文章编号</param>
        /// <returns></returns>
        [Authentication]
        public ActionResult Release(int id)
        {
            //获得文章信息
            var article = _dbContext.Articles.FirstOrDefault(a => a.ArticleID == id);

            //判断获得的文章是否是是发布
            if (article.IsRelease == 0)
                article.IsRelease = 1;
            else
                article.IsRelease = 0;

            _dbContext.SaveChanges();

            return RedirectToAction("Index");
        }

        /// <summary>
        /// 详细信息查看
        /// </summary>
        /// <param name="id">文章编号</param>
        /// <returns></returns>
        [ValidateInput(false)]
        [Authentication]
        public ActionResult Details(int id, string pageId)
        {
            ViewBag.PageId = pageId;

            var article = _dbContext.Articles.FirstOrDefault(m => m.ArticleID == id);

            return View(article);
        }

        /// <summary>
        /// Get 提交文章新建页面
        /// </summary>
        /// <returns></returns>
        [Authentication]
        public ActionResult Create(string pageId)
        {
            //绑定分类下拉框
            var categoryNamelist = LoadCategoryName();
            ViewData["categoryName"] = categoryNamelist;

            ViewBag.PageId = pageId;

            return View();
        }

        /// <summary>
        /// 新增文章
        /// </summary>
        /// <param name="articleAndCategory">文章实体</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(ArticleAndCategory articleAndCategory)
        {
            //获得当前用户信息
            CurrentUserInfo user = SecurityHelper.GetCurrentUserInfo();

            //获得保存图片名称
            string saveAsUrl = SaveAsIcon();

            //创建文章实体对象
            Article article = new Article();
            article.CategoryID = int.Parse(Request["ddlCategoryName"]);
            article.Editor = user.Name;
            article.Title = articleAndCategory.Title;
            article.Contents = articleAndCategory.Contents == null ? "暂无内容" : articleAndCategory.Contents;
            article.Icon = saveAsUrl.Contains("notShow.jpg") ? article.Icon : saveAsUrl;
            article.Description = articleAndCategory.Description;
            article.CreateTime = DateTime.Now;
            article.LastEditor = user.Name;
            article.LastEditTime = DateTime.Now;
            article.ControllorName = null;
            article.ActionName = null;
            article.IsRelease = 0;

            _dbContext.Articles.AddObject(article);
            _dbContext.SaveChanges();

            return RedirectToAction("Index");
        }
        
        /// <summary>
        /// 保存图标
        /// </summary>
        /// <returns>上传的路径</returns>
        [NonAction]
        private string SaveAsIcon()
        {
            string fileName = string.Empty;
            foreach (string upload in Request.Files)
            {
                string path = Server.MapPath(ConfigurationHelper.UplodeImagesPath);
                fileName = Guid.NewGuid().ToString() + Path.GetExtension(Request.Files[upload].FileName);
                if (Path.GetExtension(Request.Files[upload].FileName).Length != 0)
                {
                    Request.Files[upload].SaveAs(Path.Combine(path, fileName));
                }
                else
                {
                    fileName = "notShow.jpg";
                }
            }
            return fileName;
        }

        /// <summary>
        /// 文章修改Get请求
        /// </summary>
        /// <param name="id">文章编号</param>
        /// <returns></returns>
        [Authentication]
        public ActionResult Edit(int id, string pageId)
        {
            ViewBag.PageId = pageId;

            var article = _dbContext.Articles.FirstOrDefault(m => m.ArticleID == id);

            //绑定分类下拉框
            var categoryNamelist = LoadCategoryName();
            categoryNamelist.SingleOrDefault(s => s.Value.Trim() == article.CategoryID.ToString()).Selected = true;
            ViewData["categoryName"] = categoryNamelist;

            return View(article);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(Article article, string pageId)
        {
            //获得当前用户信息
            CurrentUserInfo user = SecurityHelper.GetCurrentUserInfo();

            //获得保存图片名称
            string fileName = SaveAsIcon();

            var editarticle = _dbContext.Articles.FirstOrDefault(a => a.ArticleID == article.ArticleID);

            editarticle.CategoryID = int.Parse(Request["ddlCategoryNames"]);
            editarticle.Contents = article.Contents;
            editarticle.Title = article.Title;
            //如果不上传图片，则将原来的图标路径更新至数据库
            editarticle.Icon = fileName == string.Empty ? article.Icon : ConfigurationHelper.UplodeImagesPath + fileName;
            editarticle.Description = article.Description;
            editarticle.LastEditor = user.Name;
            editarticle.LastEditTime = DateTime.Now;

            _dbContext.SaveChanges();

            return RedirectToAction("Index");
        }

        /// <summary>
        /// 文章删除
        /// </summary>
        /// <param name="id">文章ID</param>
        /// <returns></returns>
        [Authentication]
        public ActionResult Delete(int id)
        {
            Article article = _dbContext.Articles.FirstOrDefault(a => a.ArticleID == id);
            _dbContext.Articles.DeleteObject(article);

            _dbContext.SaveChanges();

            return RedirectToAction("Index");
        }

    }
}
